package com.omronservice.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.omronservice.utils.ResultMsg;
import com.omronservice.utils.ResultStatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HTTPBearerAuthorizeAttribute implements Filter {
    @Autowired
    private Audience audienceEntity;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ResultMsg resultMsg;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestMethod = httpRequest.getMethod();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization");
        if ("OPTIONS".equals(requestMethod)) {
            httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
            httpResponse.getWriter().write("");
        } else {
            String auth = httpRequest.getHeader("Authorization");
            if ((auth != null) && (auth.length() > 7)) {
                String HeadStr = auth.substring(0, 6).toLowerCase();
                if (HeadStr.compareTo("bearer") == 0) {
                    auth = auth.substring(7, auth.length());
                    if (JwtHelper.parseJWT(auth, audienceEntity.getBase64Secret()) != null) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            ObjectMapper mapper = new ObjectMapper();
            resultMsg = new ResultMsg(ResultStatusCode.INVALID_TOKEN.getResultCode(), ResultStatusCode.INVALID_TOKEN.getResultMessage(), null);
            httpResponse.getWriter().write(mapper.writeValueAsString(resultMsg));
        }
    }

    @Override
    public void destroy() {
    }
}
